package cloud.hadoop.bds.service.serviceImp;

import cloud.hadoop.bds.mapper.UserMapper;
import cloud.hadoop.bds.model.common.Result;
import cloud.hadoop.bds.pojo.User;
import cloud.hadoop.bds.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiceImp implements UserService
{

    @Autowired
    UserMapper userMapper;

    @Override
    public Result checkUser(User user)
    {
        //创建条件构造器，并为其构造条件
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq("account", user.getAccount()).eq("password", user.getPassword());
        //从数据库中返回的数据
        User account = userMapper.selectOne(wrapper);
        if (account == null)
        {
            return Result.notFound();
        }
//        return Result.successToken("admin-accessToken", "success", user);
        user.setAccessToken("admin-accessToken");
        System.out.println(user);
        return Result.success("登录成功", user);
    }

    @Override
    public Result registerUser(User user)
    {
        //把用户数据插入数据库
        userMapper.insert(user);
        return Result.success();
    }

    @Override
    public Result selectUser(Integer pageNum, Integer pageSize)
    {
        //对用户数据进行分页
        Page<User> page = new Page<>(pageNum, pageSize);
        Page<User> userList = (Page<User>) userMapper.selectPage(page, null);
        if (userList == null)
        {
            Result.notFound();
        }
        return Result.success("success", userList);
    }

    @Override
    public Result selectLikeUser(String account)
    {
        //创建条件构造器。对传进来的参数进行模糊查询
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.like("account", account);
        List<User> userList = userMapper.selectList(wrapper);
        if (userList == null)
        {
            return Result.notFound();
        }
        return Result.success("success", userList);
    }

    @Override
    public Result deleteUser(Integer id)
    {
        userMapper.deleteById(id);
        return Result.success();
    }

    @Override
    public Result updateUser(User user)
    {
        //创建条件构造器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        //更新数据对象
        userMapper.update(user, wrapper.eq("id", user.getId()));
        System.out.println(user);
        return Result.success();
    }
}
